package com.search.aibj.controller;

import com.alibaba.fastjson2.JSONObject;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import com.search.aibj.service.AibjService;
import com.search.aibj.entity.Aibj;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Aibj的路由接口服务
 * 
 * @author 
 *
 */
@Slf4j
@RestController
public class AibjController {

	/** AibjService服务 */
	@Autowired
	private AibjService aibjService;


	@GetMapping(value = "/aibj/search", produces = {"application/json;charset=UTF-8"})
	public List<Aibj> search(Aibj value) {
		return aibjService.find(value);
	}

	Document getPage(String url){
		Document doc = null;

		try{
			Connection connection = Jsoup.connect(url).proxy("127.0.0.1",10809);
			doc = connection.get();
			log.info("请求成功"+url);
			return doc;
		}catch (Exception e){
			log.error("http请求出错"+url,e);
			return getPage(url);
		}

	}

	@RequestMapping("/data")
	public int data(){

		Document doc=null;
		JSONObject result = new JSONObject();
		//url = url+"/?start="+bookSum+"&type=S";
		List<JSONObject> urls = null;
		int sum=0;
		int page = 1;
		do{
			try{
				int currentPageBookSum = 0;
				try{
					String url = "https://www.aibj.fun/forum.php?mod=forumdisplay&fid=16&filter=author&orderby=dateline&page="+page;
					doc = getPage(url);
					page++;

				}catch (Exception e){
					log.error("请求列表出错",e);

				}

				Elements threadlisttableids = doc.select("#threadlisttableid");
				if(threadlisttableids.size()>0) {
					Element threadlisttableid = threadlisttableids.get(0);
					Elements tbodys = threadlisttableid.select("tbody");

					for (int i = 0; i < tbodys.size(); i++) {

						Element element = tbodys.get(i);
						String idAttr = element.attr("id");
						if(idAttr.startsWith("normalthread_")){
							Elements xsts = element.getElementsByClass("xst");

							if(xsts.size()>0){
								Element xst = xsts.get(0);
								String name = xst.text().trim();
								String id = xst.attr("href");
								Element by = element.getElementsByClass("by").get(0);
								String date = by.select("span").get(0).text().trim();

								Aibj aibj = new Aibj();
								aibj.setName(name);
								aibj.setDate(getDate(date));
								aibj.setId(id);
								// 详情页
								getText(aibj);
								try{
									aibjService.saveNotNull(aibj);
									sum++;
								}catch (DuplicateKeyException e){
									//log.info("插入出错"+id+e,e);
								}catch (Exception e1){
									log.error("插入出错"+id+e1,e1);
								}

								log.info("插入成功"+id);
							}
						}
					}
				}
			}catch (Exception e){
				log.error("请求列表出错"+page,e);
			}
			//翻页
		}while (page<107);

		return sum;
	}

	String getDate(String date){
		try{
			DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDateTime now = LocalDateTime.now();
			if(date.contains("-")){
				return date;
			}else if(date.contains("小时前")){
				int hour = getNum(date);
				LocalDateTime past = now.minusHours(hour);
				return format.format(past);
			}else if(date.contains("天前")){
				int day = getNum(date);
				LocalDateTime past = now.minusDays(day);
				return format.format(past);
			}else if(date.contains("昨天")){
				LocalDateTime past = now.minusDays(1);
				return format.format(past);
			}else if(date.contains("前天")){
				LocalDateTime past = now.minusDays(2);
				return format.format(past);
			}
		}catch (Exception e){
			log.error("时间格式错误",e);
		}

		return "";
	}

	int getNum(String str){
		Pattern pattern = Pattern.compile("\\d+");
		// 创建 matcher 对象
		Matcher matcher = pattern.matcher(str);

		// 查找所有匹配项
		while (matcher.find()) {
			// 打印每个匹配的数字
			return Integer.parseInt(matcher.group());
		}
		return 0;
	}

	public void getText(Aibj aibj) throws InterruptedException {

		StringBuilder builder = new StringBuilder();

		try{

			Document document = getPage("https://www.aibj.fun/"+aibj.getId());
			//aibj.setOriginalHtml(document.toString());
			Elements tfs = document.getElementsByClass("t_f");
			if(tfs.size()>0){
				Element tf = tfs.get(0);
				String context = tf.html();
				String chinesePattern = "[\\u4e00-\\u9fa5]+";
				Pattern pattern = Pattern.compile(chinesePattern);
				Matcher matcher = pattern.matcher(context);
				// 提取并打印所有匹配的中文字符
				while (matcher.find()) {
					builder.append(matcher.group()+",");
				}
			}
			aibj.setText(builder.toString());
		}catch (Exception e){
			log.error("请求详情出错"+aibj.getId(),e);
		}
		Thread.sleep(10000);
	}
	
	/**
	 * 查询所有Aibj数据的方法
	 * @param value
	 * @return
	 */
	@GetMapping(value = "/Aibj", produces = {"application/json;charset=UTF-8"})
	public List<Aibj> find(Aibj value) {
		return aibjService.find(value);
	}
	
	/**
	 * 通过id查询Aibj数据的方法
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/Aibj/{id}", produces = {"application/json;charset=UTF-8"})
	public Aibj findOne(@PathVariable(name="id") String id) {
		return aibjService.findOne(id);
	}
	
	/**
	 * 插入Aibj属性不为空的数据方法
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/Aibj", produces = {"application/json;charset=UTF-8"})
	public int save(Aibj value) {
		return aibjService.saveNotNull(value);
	}
	
	/**
	 * 更新Aibj属性不为空的数据方法
	 * @param id
	 * @return
	 */
	@PutMapping(value = "/Aibj", produces = {"application/json;charset=UTF-8"})
	public int update(Aibj value) {
		return aibjService.updateNotNullById(value);
	}
	
	/**
	 * 通过id删除Aibj数据方法
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/Aibj/{id}", produces = {"application/json;charset=UTF-8"})
	public int delete(@PathVariable(name="id") String id) {
		return aibjService.deleteById(id);
	}
}
